import { contextBridge, ipcRenderer } from 'electron'
import { electronAPI } from '@electron-toolkit/preload'

// Custom APIs for renderer
const api = {
  // 窗口控制API
  minimizeWindow: () => ipcRenderer.invoke('window-minimize'),
  maximizeWindow: () => ipcRenderer.invoke('window-maximize'),
  // 恢复窗口（从最小化或最大化恢复为正常大小）
  restoreWindow: () => ipcRenderer.invoke('window-restore'),
  closeWindow: () => ipcRenderer.invoke('window-close'),
  isMaximized: () => ipcRenderer.invoke('window-is-maximized'),
  // 查询窗口是否最小化
  isMinimized: () => ipcRenderer.invoke('window-is-minimized'),

  // 窗口状态变化监听
  onWindowStateChange: callback => {
    ipcRenderer.on('window-state-changed', (event, state) => {
      callback(state)
    })
  },

  // 更新相关API
  updater: {
    // 检查更新
    checkForUpdates: () => ipcRenderer.invoke('updater-check'),
    // 下载更新
    downloadUpdate: () => ipcRenderer.invoke('updater-download'),
    // 安装更新
    installUpdate: () => ipcRenderer.invoke('updater-install'),
    // 监听更新消息
    onMessage: callback => {
      const handler = (event, message) => callback(message)
      ipcRenderer.on('updater-message', handler)
      // 返回取消监听的函数
      return () => ipcRenderer.removeListener('updater-message', handler)
    },
    // 移除所有监听器
    removeAllListeners: () => {
      ipcRenderer.removeAllListeners('updater-message')
    }
  }
}

// Use `contextBridge` APIs to expose Electron APIs to
// renderer only if context isolation is enabled, otherwise
// just add to the DOM global.
if (process.contextIsolated) {
  try {
    contextBridge.exposeInMainWorld('electron', electronAPI)
    contextBridge.exposeInMainWorld('electronAPI', api)
    contextBridge.exposeInMainWorld('api', api)
  } catch (error) {
    console.error(error)
  }
} else {
  window.electron = electronAPI
  window.electronAPI = api
  window.api = api
}
